<template>
    <div class="user-view">
        <div class="container">
            <!-- 用户信息卡片 -->
            <el-card class="user-card" shadow="never">
                <div class="user-info">
                    <el-avatar :size="100" :src="avatarUrl">
                        <el-icon>
                            <User />
                        </el-icon>
                    </el-avatar>
                    <h3 class="username">{{ username || '用户' }}</h3>
                    <p class="account">账号: {{ account || '' }}</p>
                </div>
            </el-card>

            <!-- 功能菜单 -->
            <el-card class="menu-card" shadow="never">
                <div class="menu-list">
                    <div class="menu-item" @click="handleMenuClick('profile')">
                        <div class="menu-left">
                            <el-icon>
                                <UserFilled />
                            </el-icon>
                            <span>我的资料</span>
                        </div>
                        <el-icon class="menu-arrow">
                            <ArrowRight />
                        </el-icon>
                    </div>

                    <div class="menu-item" @click="handleMenuClick('collection')">
                        <div class="menu-left">
                            <el-icon>
                                <Star />
                            </el-icon>
                            <span>我的收藏</span>
                        </div>
                        <el-icon class="menu-arrow">
                            <ArrowRight />
                        </el-icon>
                    </div>

                    <div class="menu-item" @click="handleLogout">
                        <div class="menu-left">
                            <el-icon>
                                <SwitchButton />
                            </el-icon>
                            <span>退出登录</span>
                        </div>
                        <el-icon class="menu-arrow">
                            <ArrowRight />
                        </el-icon>
                    </div>
                </div>
            </el-card>

            <!-- 返回首页按钮 -->
            <div class="back-home">
                <el-button type="primary" size="large" @click="router.push('/home')" plain>
                    <el-icon>
                        <HomeFilled />
                    </el-icon>
                    返回首页
                </el-button>
            </div>
        </div>

        <!-- 用户信息弹窗 -->
        <el-dialog v-model="profileDialogVisible" title="我的资料" width="500px" :close-on-click-modal="false"
            @close="handleDialogClose">
            <div class="profile-content">
                <!-- 账号信息（只读） -->
                <div class="profile-item">
                    <label>账号：</label>
                    <span>{{ userInfo.account || '' }}</span>
                </div>

                <!-- 用户名（可编辑） -->
                <div class="profile-item">
                    <label>用户名：</label>
                    <div class="profile-edit-wrapper">
                        <el-input v-if="isEditingUsername" v-model="editingUsername" ref="usernameInputRef" size="small"
                            maxlength="20" show-word-limit @blur="saveUsername" @keyup.enter="saveUsername" />
                        <div v-else class="profile-display" @click="startEditUsername">
                            <span>{{ userInfo.username || '未设置' }}</span>
                            <el-icon class="edit-icon">
                                <Edit />
                            </el-icon>
                        </div>
                    </div>
                </div>

                <!-- 性别（可编辑） -->
                <div class="profile-item">
                    <label>性别：</label>
                    <el-select v-model="userInfo.gender" size="small" placeholder="请选择性别" style="width: 200px"
                        @change="saveGender">
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                        <el-option label="保密" value="保密" />
                    </el-select>
                </div>

                <!-- 头像（可编辑） -->
                <div class="profile-item">
                    <label>头像：</label>
                    <div class="avatar-upload-wrapper">
                        <el-avatar :size="80" :src="userInfo.imgUrl ? getFullImageUrl(userInfo.imgUrl) : ''"
                            class="avatar-display" @click="triggerAvatarUpload">
                            <el-icon>
                                <User />
                            </el-icon>
                        </el-avatar>
                        <input type="file" ref="avatarInputRef" accept="image/*" style="display: none"
                            @change="handleAvatarChange" />
                        <el-button type="primary" size="small" @click="triggerAvatarUpload">
                            <el-icon>
                                <Upload />
                            </el-icon>
                            上传头像
                        </el-button>
                    </div>
                </div>

                <!-- 注册时间（只读） -->
                <div class="profile-item">
                    <label>注册时间：</label>
                    <span>{{ formatDateTime(userInfo.createAt) || '' }}</span>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    User,
    UserFilled,
    Star,
    SwitchButton,
    HomeFilled,
    ArrowRight,
    Edit,
    Upload
} from '@element-plus/icons-vue'
import { host, getCurrentUserDetail, editCurrentUser, uploadPhoto } from '../api/index'

const router = useRouter()
const avatarUrl = ref<string>('')
const username = ref<string>('')
const account = ref<string>('')

// 弹窗相关
const profileDialogVisible = ref<boolean>(false)
const userInfo = ref<{
    account: string
    username: string
    gender: string
    imgUrl: string
    createAt: string
}>({
    account: '',
    username: '',
    gender: '',
    imgUrl: '',
    createAt: ''
})

// 用户名编辑相关
const isEditingUsername = ref<boolean>(false)
const editingUsername = ref<string>('')
const usernameInputRef = ref<any>(null)
const avatarInputRef = ref<HTMLInputElement | null>(null)

// 获取完整图片URL
const getFullImageUrl = (imgUrl: string) => {
    if (!imgUrl) return ''
    // 如果已经是完整URL，直接返回
    if (imgUrl.startsWith('http://') || imgUrl.startsWith('https://')) {
        return imgUrl
    }
    // 相对路径，确保以 / 开头
    const urlPath = imgUrl.startsWith('/') ? imgUrl : '/' + imgUrl
    return host + urlPath
}

// 加载用户信息
const loadUserInfo = async () => {
    const token = localStorage.getItem('AUTO_TOKEN')
    const storedUsername = localStorage.getItem('USERNAME')
    const storedAvatar = localStorage.getItem('USER_AVATAR')

    if (token) {
        // 先从localStorage获取
        username.value = storedUsername || '用户'
        if (storedAvatar) {
            avatarUrl.value = getFullImageUrl(storedAvatar)
        }

        // 从服务器获取最新信息
        try {
            const resData = await getCurrentUserDetail()
            if (resData && resData.code === 200 && resData.data) {
                const userData = resData.data
                // 更新用户名
                if (userData.username) {
                    username.value = userData.username
                    localStorage.setItem("USERNAME", userData.username)
                }
                // 更新账号
                if (userData.account) {
                    account.value = userData.account
                }
                // 更新头像
                if (userData.imgUrl) {
                    avatarUrl.value = getFullImageUrl(userData.imgUrl)
                    localStorage.setItem("USER_AVATAR", userData.imgUrl)
                } else {
                    avatarUrl.value = ''
                    localStorage.removeItem("USER_AVATAR")
                }
            }
        } catch (error) {
            console.error('获取用户信息失败:', error)
        }
    } else {
        // 未登录，跳转到登录页
        router.push('/login')
    }
}

onMounted(() => {
    loadUserInfo()
})

const handleMenuClick = (type: string) => {
    if (type === 'collection') {
        // 跳转到收藏列表
        router.push('/favorite')
    } else if (type === 'profile') {
        // 打开用户资料弹窗
        openProfileDialog()
    } else {
        ElMessage.info(`${type} 功能开发中...`)
    }
}

// 打开用户资料弹窗
const openProfileDialog = async () => {
    profileDialogVisible.value = true
    await loadUserInfoForDialog()
}

// 关闭弹窗
const handleDialogClose = () => {
    isEditingUsername.value = false
    editingUsername.value = ''
}

// 为弹窗加载用户信息
const loadUserInfoForDialog = async () => {
    try {
        const resData = await getCurrentUserDetail()
        if (resData && resData.code === 200 && resData.data) {
            const userData = resData.data
            userInfo.value = {
                account: userData.account || '',
                username: userData.username || '',
                gender: userData.gender || '',
                imgUrl: userData.imgUrl || '',
                createAt: userData.createAt || ''
            }
        }
    } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
    }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
    if (!dateTimeStr) return ''
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 开始编辑用户名
const startEditUsername = () => {
    isEditingUsername.value = true
    editingUsername.value = userInfo.value.username
    nextTick(() => {
        if (usernameInputRef.value) {
            usernameInputRef.value.focus()
        }
    })
}

// 保存用户名
const saveUsername = async () => {
    if (!editingUsername.value || !editingUsername.value.trim()) {
        ElMessage.error('用户名不能为空')
        isEditingUsername.value = false
        return
    }

    const newUsername = editingUsername.value.trim()
    if (newUsername === userInfo.value.username) {
        isEditingUsername.value = false
        return
    }

    try {
        const resData = await editCurrentUser({
            username: newUsername,
            gender: userInfo.value.gender,
            imgUrl: userInfo.value.imgUrl
        })

        if (resData && resData.code === 200) {
            userInfo.value.username = newUsername
            username.value = newUsername
            localStorage.setItem("USERNAME", newUsername)
            ElMessage.success('用户名修改成功')
            isEditingUsername.value = false
            // 触发更新事件
            window.dispatchEvent(new Event('storage'))
        } else {
            ElMessage.error(resData.msg || '用户名修改失败')
        }
    } catch (error) {
        console.error('保存用户名失败:', error)
        ElMessage.error('保存用户名失败，请稍后重试')
    }
}

// 保存性别
const saveGender = async () => {
    try {
        const resData = await editCurrentUser({
            username: userInfo.value.username,
            gender: userInfo.value.gender,
            imgUrl: userInfo.value.imgUrl
        })

        if (resData && resData.code === 200) {
            ElMessage.success('性别修改成功')
        } else {
            ElMessage.error(resData.msg || '性别修改失败')
        }
    } catch (error) {
        console.error('保存性别失败:', error)
        ElMessage.error('保存性别失败，请稍后重试')
    }
}

// 触发头像上传
const triggerAvatarUpload = () => {
    if (avatarInputRef.value) {
        avatarInputRef.value.click()
    }
}

// 处理头像文件选择
const handleAvatarChange = async (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]
    if (!file) return

    // 验证文件类型
    if (!/\.(jpe?g|png|gif|bmp|webp)/i.test(file.name)) {
        ElMessage.error('请选择图片格式的文件')
        return
    }

    // 验证文件大小（限制5MB）
    if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过5MB')
        return
    }

    try {
        // 创建FormData
        const formData = new FormData()
        formData.append('photo', file)

        // 上传图片
        const uploadRes = await uploadPhoto(formData)
        if (uploadRes && uploadRes.code === 200 && uploadRes.picUrl) {
            // 更新用户信息
            const updateRes = await editCurrentUser({
                username: userInfo.value.username,
                gender: userInfo.value.gender,
                imgUrl: uploadRes.picUrl
            })

            if (updateRes && updateRes.code === 200) {
                ElMessage.success('头像上传成功')
                // 更新本地显示
                userInfo.value.imgUrl = uploadRes.picUrl
                avatarUrl.value = getFullImageUrl(uploadRes.picUrl)
                localStorage.setItem("USER_AVATAR", uploadRes.picUrl)
                // 触发更新事件
                window.dispatchEvent(new Event('storage'))
            } else {
                ElMessage.error(updateRes.msg || '头像上传失败')
            }
        } else {
            ElMessage.error(uploadRes.msg || '头像上传失败')
        }
    } catch (error) {
        console.error('上传头像失败:', error)
        ElMessage.error('上传头像失败，请稍后重试')
    } finally {
        // 清空input，以便可以重复选择同一文件
        if (target) {
            target.value = ''
        }
    }
}

const handleLogout = () => {
    ElMessageBox.confirm(
        '确定要退出登录吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        localStorage.removeItem('AUTO_TOKEN')
        localStorage.removeItem('USERNAME')
        localStorage.removeItem('USER_ROLE')
        localStorage.removeItem('USER_AVATAR')
        // 触发自定义事件通知 LayoutView 更新
        window.dispatchEvent(new Event('storage'))
        ElMessage.success('已退出登录')
        router.push('/login')
    })
}
</script>

<style lang="less" scoped>
@import "../assets/varable.less";

.user-view {
    min-height: calc(100vh - 300px);
    padding: 40px 0;

    .user-card {
        border-radius: 16px;
        margin-bottom: 20px;

        .user-info {
            text-align: center;
            padding: 30px;

            .username {
                font-size: 24px;
                font-weight: 600;
                color: @text-primary;
                margin: 20px 0 10px;
            }

            .account {
                color: @text-secondary;
                margin: 0;
            }
        }
    }

    .menu-card {
        border-radius: 16px;
        margin-bottom: 30px;

        :deep(.el-card__body) {
            padding: 0;
        }

        .menu-list {
            .menu-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 18px 20px;
                border-bottom: 1px solid @border-light;
                cursor: pointer;
                transition: all 0.3s;

                &:last-child {
                    border-bottom: none;
                }

                &:hover {
                    background: @primary-lighter;
                }

                .menu-left {
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    color: @text-primary;
                    font-size: 16px;

                    .el-icon {
                        font-size: 20px;
                        color: @primary-color;
                    }
                }

                .menu-arrow {
                    color: @text-light;
                    font-size: 16px;
                }
            }
        }
    }

    .back-home {
        text-align: center;

        .el-button {
            width: 100%;
            max-width: 300px;
        }
    }
}

// 弹窗样式
:deep(.el-dialog) {
    .profile-content {
        padding: 20px 0;

        .profile-item {
            display: flex;
            align-items: center;
            margin-bottom: 24px;

            &:last-child {
                margin-bottom: 0;
            }

            label {
                width: 100px;
                font-weight: 500;
                color: @text-primary;
                flex-shrink: 0;
            }

            span {
                color: @text-secondary;
            }

            .profile-edit-wrapper {
                flex: 1;

                .profile-display {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    padding: 8px 12px;
                    border: 1px solid @border-light;
                    border-radius: 4px;
                    cursor: pointer;
                    transition: all 0.3s;
                    color: @text-primary;

                    &:hover {
                        border-color: @primary-color;
                        background: @primary-lighter;

                        .edit-icon {
                            color: @primary-color;
                        }
                    }

                    .edit-icon {
                        font-size: 16px;
                        color: @text-light;
                        transition: color 0.3s;
                    }
                }
            }

            .avatar-upload-wrapper {
                display: flex;
                align-items: center;
                gap: 16px;

                .avatar-display {
                    cursor: pointer;
                    transition: all 0.3s;

                    &:hover {
                        opacity: 0.8;
                        transform: scale(1.05);
                    }
                }
            }
        }
    }
}
</style>
